package cn.easyutil.util.javaUtil;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.easyutil.util.javaUtil.bean.IpAddressBean;

public class IpUtil {

	/**
	 * 获取本机内网ip
	 * 
	 * @return
	 */
	public static String getLocalIp() {
		InetAddress ia;
		try {
			ia = InetAddress.getLocalHost();
			String ip = ia.toString().split("/")[1];
			return ip;
		} catch (UnknownHostException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 获取本机公网ip
	 * 
	 * @return
	 */
	public static String getPublicIp() {
		try {
			String ip = "";
			String chinaz = "http://ip.chinaz.com";

			String result = HttpUtil.doUrl(chinaz, "GET");
			Pattern p = Pattern.compile("\\<dd class\\=\"fz24\">(.*?)\\<\\/dd>");
			Matcher m = p.matcher(result);
			if (m.find()) {
				String ipstr = m.group(1);
				ip = ipstr;
			}
			return ip;
		} catch (Exception e) {
			throw new RuntimeException("方法内部错误");
		}
	}

	/**
	 * 获取本机mac地址
	 * 
	 * @return
	 */
	public static String getLocalMac() {
		// 获取网卡，获取地址
		byte[] mac;
		try {
			mac = NetworkInterface.getByInetAddress(InetAddress.getLocalHost()).getHardwareAddress();
			StringBuffer sb = new StringBuffer("");
			for (int i = 0; i < mac.length; i++) {
				if (i != 0) {
					sb.append("-");
				}
				// 字节转换为整数
				int temp = mac[i] & 0xff;
				String str = Integer.toHexString(temp);
				if (str.length() == 1) {
					sb.append("0" + str);
				} else {
					sb.append(str);
				}
			}
			return sb.toString();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 获取公网ip的地址及运营商
	 * 
	 * @param publicIp
	 *            公网ip
	 * @return
	 */
	public static IpAddressBean getIpAddress(String publicIp) {
		String url = "http://ip.taobao.com/service/getIpInfo.php?ip=" + publicIp;
		String address = HttpUtil.doUrl(url, "GET");
		Map<String, Object> map = JsonUtil.jsonToMap(address);
		if (map.get("code").equals(0)) {
			@SuppressWarnings("unchecked")
			Map<String, Object> data = (Map<String, Object>) map.get("data");
			IpAddressBean bean = JsonUtil.mapToBean(data, IpAddressBean.class);
			return bean;
		}
		throw new RuntimeException("error:" + address);
	}

}
